有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在执行shell命令时显示progressbar

我试图在复制文件的过程中(使用shell命令)显示一个进度条。这是我的密码:

    copyProgress = new ProgressDialog(Activ.this);
    copyProgress.setMessage("Copying");
    copyProgress.show();  

    Process process1 = Runtime.getRuntime().exec(new String[] {"cp /sdcard/file /system"});
    Process process2 = Runtime.getRuntime().exec(new String[] {"cp /sdcard/file2 /system"});
    .......

    copyProgress.dismiss();

我需要执行多个不同的进程,因此如何才能在开始时显示进度对话框,并在最后一个文件成功完成复制后将其取消。我尝试在proccess1之前显示对话框,在最后一个进程之后关闭对话框,但这不起作用。谢谢

显然我需要用线把它包起来。有人能告诉我怎么做吗


共 (1) 个答案

  1. # 1 楼答案

    您的原始代码中有几个问题。下面的代码在后台线程上处理进程的运行,并使用waitFor调用检查其结果。所有这些都是毫无意义的,因为没有root用户就无法复制到/system

    {   
       copyProgress = new ProgressDialog(Activ.this);
       copyProgress.setMessage("Copying");
       copyProgress.show();  
       new DoShellScriptyThingsAsyncThread().execute();
    }
    
    private class DoShellScriptyThingsAsyncThread extends AsyncTask<Void,Void,Void>
    {
    
        @Override
        protected Void doInBackground(Void... params) {
    
            doCopy("file");
            publishProgress();
            doCopy("file2");
            publishProgress()
            return null;
        }
    
        private void  doCopy(String filename)
        {
            try    
        {            
    
            Process proc = Runtime.getRuntime().exec(new String[] {"cp /sdcard/"  +filename +" /system"});
            InputStream stdin = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(stdin);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            System.out.println("<OUTPUT>");
            while ( (line = br.readLine()) != null)
                System.out.println(line);
            System.out.println("</OUTPUT>");
            int exitVal = proc.waitFor();            
            System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t)
          {
            t.printStackTrace();
            //Now do some thing if this fails - which it will because you are trying
            // to copy something to system
          }
    }
        @Override
        protected void onProgressUpdate(Void... updateInteger)
        {
            //Update your progress dialog here!
            copyProgress.incrementProgress(5000);
        }
      }
        @Override
        protected void onPostExecute(Void result)
        {
            //Make your progress dialog go away here
            copyProgress.dismiss();
        }
    
    };